package community.application.service;

import community.domain.model.Comment;
import community.domain.repository.CommentRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CommentService {

    private final CommentRepository commentRepository;

    public Comment createComment(Comment comment) {
        return commentRepository.save(comment);
    }

    public Optional<Comment> getCommentById(Long id) {
        return commentRepository.findById(id);
    }

    public List<Comment> getCommentsByPostId(Long postId) {
        List<Comment> comments = commentRepository.findByPostId(postId);
        //  触发懒加载，确保 user 不为 null
        for (Comment comment : comments) {
            if (comment.getUser() != null) {
                comment.getUser().getUsername(); // 触发 user 懒加载
            }
        }
        return comments;
    }

    public List<Comment> getRepliesByParentId(Long parentId) {
        return commentRepository.findByParentCommentId(parentId);
    }

    public void deleteComment(Long id) {
        commentRepository.deleteById(id);
    }
}
